package org.mcjug.locationmailer.util;

import org.mcjug.locationmailer.service.LocationService;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
//import android.util.Log;

public class AlarmManagerUtil {
    private static final String TAG = LocationUtil.class.getSimpleName();

    private Context context;

    public AlarmManagerUtil(Context context) {
        this.context = context;
    }

    public void updateAlarm() {
        cancelAlarm();

        long interval = getInterval();
        if (interval != Constants.LOCATION_UPDATE_INTERVAL_NONE) {

            // Setup alarm service to wake up and start service periodically
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, interval, getPendingIntent());
        }
    }

    public void cancelAlarm() {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(getPendingIntent());
    }

    public void resetAlarm() {
        cancelAlarm();
        updateAlarm();
    }

    public PendingIntent getPendingIntent() {
        Intent intent = new Intent(context, LocationService.class);
        return PendingIntent.getService(context, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public long getInterval() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String intervalStr = prefs.getString(Constants.PREFS_LOCATION_UPDATE_INTERVAL_KEY, null);

        int interval = 43200000; // Half Day
        if (intervalStr != null) {
            try {
                interval = Integer.parseInt(intervalStr);
            } catch (NumberFormatException e) {
                //Log.e(TAG, "getInterval NumberFormatException parsing for location interval", e);
            }
        }
        return interval;
    }
}
